package com.yougou.ui.search;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yougou.base.BaseViewModel;
import com.yougou.data.api.ApiConfig;
import com.yougou.data.model.Goods;
import com.yougou.data.repository.CategoryRepository;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SearchViewModel extends BaseViewModel {
    
    private final CategoryRepository mRepository;
    private final MutableLiveData<List<Goods>> mSearchResult = new MutableLiveData<>();
    private final MutableLiveData<String> mError = new MutableLiveData<>();
    private final MutableLiveData<Boolean> mLoading = new MutableLiveData<>(false);
    
    public SearchViewModel() {
        mRepository = new CategoryRepository();
    }
    
    public LiveData<List<Goods>> getSearchResult() {
        return mSearchResult;
    }
    
    public LiveData<String> getError() {
        return mError;
    }
    
    public LiveData<Boolean> isLoading() {
        return mLoading;
    }
    
    
    public void search(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            mError.setValue("请输入搜索关键词");
            return;
        }
        
        mLoading.setValue(true);
        addDisposable(
            mRepository.searchGoods(keyword, 1, ApiConfig.DEFAULT_PAGE_SIZE)
                .map(response -> {
                    if (response.isSuccess() && response.getMessage() != null) {
                        return response.getMessage().getGoods();
                    }
                    return null;
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    goods -> {
                        mLoading.setValue(false);
                        if (goods != null && !goods.isEmpty()) {
                            mSearchResult.setValue(goods);
                        } else {
                            mError.setValue("未找到相关商品");
                        }
                    },
                    error -> {
                        mLoading.setValue(false);
                        mError.setValue("网络错误: " + error.getMessage());
                    }
                )
        );
    }
}

